package com.yao.dubboprovider.registry.impl;

import com.yao.dubboapi.constant.ZookeeperConstant;
import com.yao.dubboprovider.registry.RegistryCenter;
import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.CuratorFrameworkFactory;
import org.apache.curator.retry.RetryOneTime;
import org.apache.zookeeper.CreateMode;

/**
 * zookeeper服务注册中心
 *
 * @author Henry Yao
 * @since 2021/5/3
 */
public class ZKRegistryCenterImpl implements RegistryCenter {
    private CuratorFramework curator;

    {
        curator = CuratorFrameworkFactory.builder()
                .namespace(ZookeeperConstant.ZK_ROOT)
                .connectString(ZookeeperConstant.ZK_ADDRESS)
                .sessionTimeoutMs(5000)
                .connectionTimeoutMs(5000)
                .retryPolicy(new RetryOneTime(2000))
                .build();
        // 记得start
        curator.start();
    }

    @Override
    public void registryService(String serviceName, String address) throws Exception {
        // 创建服务名的永久节点
        String serviceNode = "/" + serviceName;
        if (curator.checkExists().forPath(serviceNode) == null) {
            curator.create()
                    .creatingParentsIfNeeded()
                    .withMode(CreateMode.PERSISTENT)
                    .forPath(serviceNode);
        }
        // 创建提供者主机地址的临时节点
        String providerNode = serviceNode + "/" + address;
        if (curator.checkExists().forPath(providerNode) == null) {
            curator.create()
                    .creatingParentsIfNeeded()
                    .withMode(CreateMode.EPHEMERAL)
                    .forPath(providerNode);
            System.out.println("registry service " + serviceName + " on " + address + " successfully");
        }

    }

}
